package com.hh.us.web.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.hh.us.conf.DomainConf;
import com.hh.us.entity.Urls;
import com.hh.us.service.IUrlsService;

@Controller
@RequestMapping
public class USController {
	private static final Logger LOGGER = LoggerFactory.getLogger(USController.class);

	@Resource
	private IUrlsService urlsService;
	@Resource
	private DomainConf domainConf;

	@RequestMapping(value="/api/short", method = RequestMethod.GET)
    public ResponseEntity<String> shortUrl(@RequestParam(required = true) String url, HttpServletRequest request) {
		LOGGER.debug("[/api/short]-[request url]:{}", url);
        Urls urls = urlsService.shortUrl(new Urls(null, url, null));
        if(urls != null) {
        	LOGGER.debug("[/api/short]-[request url]:{}-[response url]:{}", url, urls.getSurl());
        	return new ResponseEntity<>(String.format("%s%s", getBasepath(request), urls.getSurl()), HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

	@RequestMapping(value = "/api/long", method = RequestMethod.GET)
	public ResponseEntity<String> longUrl(@RequestParam(required = true) String url) {
		LOGGER.debug("[/api/long]-[request url]:{}", url);
		url = StringUtils.contains(url, "/") ? StringUtils.substringAfterLast(url, "/") : url;
		Urls urls = urlsService.findBySurl(url);
		String lurl = urls != null ? urls.getLurl() : "long url not found";
		LOGGER.debug("[/api/long]-[request url]:{}-[response url]:{}", url, lurl);
        return new ResponseEntity<>(lurl, HttpStatus.OK);
    }

	@RequestMapping(value = "/{surl}", method = RequestMethod.GET)
    public void redirect(@PathVariable String surl, HttpServletResponse resp) throws Exception {
		LOGGER.debug("[/surl]-[request url]:{}", surl);
        Urls urls = urlsService.findBySurl(surl);
        if (urls != null && StringUtils.isNotBlank(urls.getLurl())) {
        	LOGGER.debug("[/surl]-[request url]:{}-[response url]:{}", surl, urls.getLurl());
        	resp.sendRedirect(urls.getLurl());
        } else {
        	LOGGER.debug("[/surl]-[request url]:{}-[NOT FOUND]",surl);
        	resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
	
	private String getBasepath(HttpServletRequest request) {
		String basepath = domainConf.getBasepath();
    	if(StringUtils.isBlank(basepath)) {
    		//String baseUrl = String.format("%s://%s:%d/",request.getScheme(),  request.getServerName(), request.getServerPort());
    		String baseUrl = String.format("%s://%s:%d%s/", request.getScheme(), request.getServerName(),request.getServerPort(), request.getContextPath());
    		basepath = baseUrl;
    		domainConf.setBasepath(basepath);
    		LOGGER.info("get base path : {}", basepath);
    	}
    	return basepath;
	}


}
